package com.decheng.service.impl;

import com.decheng.dao.OrderDao;
import com.decheng.dao.impl.OrderDaoImpl;
import com.decheng.pojo.*;
import com.decheng.service.OrderService;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Map;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 */
public class OrderServiceImpl implements OrderService {

    private OrderDao orderDao = new OrderDaoImpl();

    /**
     * 结账 - 创建订单
     *
     * @param user 用户, 创建订单时，需要用户id
     * @param cart 购物车，创建订单时，需要 totalCount,totalAmount
     */
    @Override
    public String checkOut(User user, Cart cart) {
        // 1. 初始化订单对象
        Order order = new Order();
        order.setUserId(user.getId());
        order.setOrderSequence(System.currentTimeMillis() + "");
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format_time = dtf.format(LocalDateTime.now());
        order.setCreateTime(format_time);
        order.setOrderStatus(0);
        order.setTotalCount(cart.getTotalCount());
        order.setTotalAmount(cart.getTotalAmount());
        // 2. 调用 Dao 层添加订单到数据库
        orderDao.saveOrder(order);
        // 3. 返回订单号
        return order.getOrderSequence();
    }

    /**
     * 创建订单项
     *
     * @param cart          购物车，根据购物项创建订单项
     * @param orderSequence 订单号, 与订单项进行关联
     */
    @Override
    public void createOrderItems(Cart cart, String orderSequence) {
        Map<Integer, CartItem> cartItemMap = cart.getCartItemMap();
        ArrayList<OrderItem> orderItems = new ArrayList<>();

        for (Map.Entry<Integer, CartItem> item : cartItemMap.entrySet()) {
            OrderItem orderItem = new OrderItem();
            CartItem cartItem = item.getValue();
            orderItem.setOrderId(orderSequence);
            orderItem.setBookName(cartItem.getBookName());
            orderItem.setImgPath(cartItem.getImgPath());
            orderItem.setPrice(cartItem.getPrice());
            orderItem.setItemAmount(cartItem.getAmount());
            orderItem.setItemCount(cartItem.getCount());
            orderItems.add(orderItem);
        }

        for (OrderItem orderItem : orderItems) {
            System.out.println(orderItem);
        }
    }
}
